<template>
  <el-dialog v-if="load" :title="title" v-model="visible" align-center width="773px" @close="handleClose" :close-on-click-modal="false">
    <el-form :model="formData" label-width="140px" :rules="rules" ref="ruleFormRef" inline class="formw200">
      <el-form-item label="平台:" prop="platform_id">
        <el-select v-model="formData.platform_id" class="input" collapse-tags placeholder="平台" @change="changePlatform">
          <el-option v-for="(d, i) in platformList" :key="i" :label="d.platform_name" :value="d.platform_id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="站点:" class="mr-[0]">
        <el-select v-model="formData.site" class="input mr-[6px]" multiple collapse-tags clearable placeholder="站点" @change="changeSite">
          <el-option v-for="(d, i) in siteList" :key="i" :label="d.site_abbrev" :value="d.site_id"></el-option>
        </el-select>
        <el-button type="primary" @click="checkAllSite">全选</el-button>
      </el-form-item>
      <el-form-item label="店铺:" class="mr-[0]">
        <el-select v-model="formData.shop_id" class="input mr-[6px]" multiple collapse-tags clearable placeholder="店铺">
          <el-option v-for="(d, i) in shopList" :key="i" :label="d.shop_name" :value="d.shop_id"></el-option>
        </el-select>
        <el-button type="primary" @click="checkAllShop">全选</el-button>
        站点/店铺不选择，则代表此平台所有站点和店铺都为以下的佣金
      </el-form-item>
      <el-form-item label="订单金额范围:" style="margin-bottom:0;">
        <el-form-item prop="lowest_selling_price" class="mr-[2px]">
          <el-input class="w-[190px]" type="number" v-model="formData.lowest_selling_price" placeholder="请输入" />
        </el-form-item>
        <span class="text-gray-500 mb-[18px] mx-[4px]">-</span>
        <el-form-item prop="highest_selling_price" class="ml-[2px] mr-[4px]">
          <el-input class="w-[190px]" type="number" v-model="formData.highest_selling_price" placeholder="请输入" />
        </el-form-item>
        <span>RMB</span>
      </el-form-item>
      <el-form-item label="佣金比例:" prop="commission_rate">
        <el-input class="input" type="number" v-model="formData.commission_rate" placeholder="请输入">
          <template #append>%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="一口价佣金:" prop="buy_it_now_commission" class="mr-[0]">
        <el-input class="input" type="number" v-model="formData.buy_it_now_commission" placeholder="请输入">
          <template #append>RMB</template>
        </el-input>
      </el-form-item>
      <el-form-item label="最低佣金:" prop="minimum_commission">
        <el-input class="input" type="number" v-model="formData.minimum_commission" placeholder="请输入">
          <template #append>RMB</template>
        </el-input>
      </el-form-item>
      <el-form-item label="附加佣金:" prop="additional_commission" class="mr-[0]">
        <el-input class="input" type="number" v-model="formData.additional_commission" placeholder="请输入">
          <template #append>RMB</template>
        </el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, toRefs } from "vue"
import { getDetail, createCommission, updateCommission } from "../api"
import { ElMessage } from "element-plus"
import XEUtils from "xe-utils"
import { getPlatformOptions, getSiteOptions, getShopOptions } from "@/api/public"

const ruleFormRef = ref()
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
// 声明接收参数
const props = defineProps({
  title: {
    type: String,
    default: "新增",
  },
  ruleTypeOption: {
    type: Object,
    default: [],
  },
})
const data = reactive({
  formData: {
    platform_id: "",
  },
  isType: false,
  platformList: [],
  siteList: [],
  shopList: [],
})
const { formData, isType, platformList, siteList, shopList } = toRefs(data)
const { title, ruleTypeOption } = toRefs(props)
const emit = defineEmits(["close", "confirm"])
//清空sku
const clearSku = () => {
  formData.value.sku = ""
}
//是否为数字
const isNumberF = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    if (!XEUtils.isNumber(value * 1)) {
      return callback(new Error("请输入数字"))
    } else {
      callback()
    }
  }
}
//订单金额范围
const priceRadius = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    if (!XEUtils.isNumber(value * 1)) {
      return callback(new Error("请输入数字"))
    }
  }
}
const rules = reactive({
  rule_name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  rule_type: [{ required: true, message: "请选择", trigger: "change" }],
  platform_id: [{ required: true, message: "请选择", trigger: "change" }],
  additional_commission: [{ validator: isNumberF, trigger: "blur" }],
  commission_rate: [{ validator: isNumberF, trigger: "blur" }],
  buy_it_now_commission: [{ validator: isNumberF, trigger: "blur" }],
  minimum_commission: [{ validator: isNumberF, trigger: "blur" }],
  close_sell_price: [{ validator: priceRadius, trigger: "blur" }],
})

// 打开弹窗
const open = (row = {}) => {
  if (!load.value) {
    load.value = true
  }
  if (row.id) {
    isType.value = true
    getDetail({ id: row.id }).then((res) => {
      loadings = reactive({})
      visible.value = true
      getSite(res.data.platform_id)
      getShop(res.data.platform_id, res.data.site)
      formData.value = res.data
    })
  } else {
    loadings = reactive({})
    isType.value = false
    visible.value = true
  }
}
// 关闭弹窗
const close = () => {
  formData.value = {}
  ruleFormRef.value.resetFields()
  visible.value = false
}

const handleClose = () => {
  close()
  emit("close")
}
// 提交
const submit = () => {
  let { validate } = ruleFormRef.value
  validate((valid) => {
    if (valid) {
      loadings.submit = true
      let keys = [
        "platform_id",
        "site",
        "shop_id",
        "additional_commission",
        "minimum_commission",
        "buy_it_now_commission",
        "commission_rate",
        "highest_selling_price",
        "lowest_selling_price",
      ]
      let params = {}
      keys.forEach((key) => {
        params[key] = formData.value[key] || ""
      })
      if (!params.shop_id || !params.shop_id.length) {
        params.shop_id = shopList.value.map((v) => v.shop_id)
      }
      if (isType.value) {
        params.id = formData.value.id
        updateCommission(params)
          .then((res) => {
            ElMessage({ message: "保存成功！", type: "success" })
            emit("confirm")
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      } else {
        createCommission(params)
          .then((res) => {
            ElMessage({ message: "保存成功！", type: "success" })
            emit("confirm")
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      }
    }
  })
}
defineExpose({ open })

// 获取平台
const getPlatform = async () => {
  try {
    const res = await getPlatformOptions()
    platformList.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

// 选择平台
const changePlatform = async (val) => {
  siteList.value = []
  shopList.value = []
  formData.value.site = ""
  formData.value.shop_id = ""
  getSite(val)
}

// 获取站点
const getSite = async (id) => {
  try {
    const res = await getSiteOptions({
      platform_ids: [id],
    })
    siteList.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

// 选择站点
const changeSite = async (val) => {
  shopList.value = []
  formData.value.shop_id = ""
  getShop(formData.value.platform_id, val)
}

// 获取店铺列表
const getShop = async (platform_id, site_ids) => {
  try {
    const res = await getShopOptions({
      site_ids,
      platform_ids: [platform_id],
    })
    shopList.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

// 全选站点
const checkAllSite = async () => {
  if (siteList.value.length == 0) {
    ElMessage.error("站点列表为空")
    return
  }
  const site_ids = siteList.value.map((i) => i.site_id)
  formData.value.site = site_ids
  getShop(formData.value.platform_id, site_ids)
}

// 全选店铺
const checkAllShop = async () => {
  if (shopList.value.length == 0) {
    ElMessage.error("店铺列表为空")
    return
  }
  const shop_ids = shopList.value.map((i) => i.shop_id)
  formData.value.shop_id = shop_ids
}

onMounted(() => {
  getPlatform()
})
</script>
<style lang="scss" scoped>
.formw200 {
  .el-form-item {
    // width: 400px;
    margin-right: 12px;
    // .el-input{
    //   width: 400px;
    // }
  }
  .input {
    width: 400px;
  }
}
:deep(input::-webkit-outer-spin-button),
:deep(input::-webkit-inner-spin-button) {
  -webkit-appearance: none !important;
}
:deep(.el-input__inner) {
  line-height: 1px !important;
}
</style>
